﻿$.extend($, {
    HOSTS: {
        configUrl: {
            'loc': '//' + location.host + '/',
            // ******>> 外部接口或固定值 配置 <<******
            'dev.def': '//121.40.217.110:886/',
            'test.def': '//10.70.100.225/',
            'prd.def': '//sxapp.zj.chinamobile.com/',

            'dev.shaoxin': '//'+location.host+'/',
            'sit.shaoxin': '//10.70.100.225/',
            'prd.shaoxin': '//sxapp.zj.chinamobile.com/'
        }
    },
    /* 获取host地址
    *  forceSec 为true强制走生产
    * */
    getAjaxHost: function(type, forceSec) {
        var nowUrl = location.href;
        var protocol = location.protocol;
        var env = ''; // 环境
        var HOSTS = this.HOSTS.configUrl;
        var host = '';
        // 1.判断环境
        if (/localhost|188.180/.test(nowUrl)) { //开发环境
            env = 'dev';
        } else if (/10.70.100.225/.test(nowUrl)) { //测试环境
            env = 'test';
        } else { //生产环境
            env = 'prd';
        }
        env = forceSec ? 'prd' : env;
        // 针对特别情况，走本地跳转需要
        if (type === 'local')
            return protocol + HOSTS.loc;
        switch (type) {
            // ****** dt服务接口 ****** 直连prd
            case 'shaoxin':
                host = HOSTS[env + '.shaoxing'];
                break;
            default:
                host = HOSTS[env + '.def'];
        }

        return /^http/.test(host) ? host : (protocol + host);
    },
    getData: function(options) {
        // var failureOptions=failureOptions;
        var dtd = $.Deferred(); //兼容zepto中promise特性
        var settings = {
            type: 'POST',
            data: {},
            timeout: 10000,
            dataType: "json",
            headers: {
                'Access-Control-Allow-Origin':'*',
                'Content-Type': 'text/plain;charset=UTF-8'
            },
            success: function () {
            },
            error: function () {
                $.alert('网络异常，请稍后重试！', 3000);
            }
        };
        $.extend(settings, options);
        $.ajax({
            type: settings.type,
            url: settings.url,
            data: settings.data,
            dataType: settings.dataType,
            headers: settings.headers,
            timeout: settings.timeout,
            contentType: settings.contentType ? settings.contentType : 'application/x-www-form-urlencoded',
            success: function (data) {
                if (data) {
                    settings.success(data);
                    dtd.resolve(data);
                } else {
                    settings.error(data);
                    dtd.reject();
                }
            },
            error: function (xhr, status, error) {
                var res = {}
                try {
                    res = JSON.parse(xhr.response)
                } catch (error) {
                }
                if(error){
                    settings.error(res);
                    dtd.reject();
                }else{
                    var fileName = settings.url.split('/')[settings.url.split('/').length-1];
                    $.ajax({
                        type: settings.type,
                        url: '../../json/'+ fileName +'.json',
                        data: settings.data,
                        dataType: settings.dataType,
                        async: false,
                        success: function (data2) {
                            settings.success(data2);
                            dtd.resolve(data2);
                        },error:function () {
                            settings.error();
                            dtd.reject();
                        }
                    });
                }
            }
        });
        return dtd.promise();
    },
    getQueryString: function(name, bBackFirst) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i" + (bBackFirst ? 'g' : ''));
        var r = window.location.search.substr(1).match(reg);
        // $.mobileConsole(r);
        var value = '';
        if (bBackFirst && r != null) {
            value = r[r.length - 1];
            value = value.replace(/^&|&$/g, '').replace(name + '=', ''); //去掉头尾的& 去掉参数等式 params=
        } else if (r != null) {
            value = r[2];
            value = value.replace(/(%22|%3E|%3C|<|>)/g, "MM");
        }
        if (value == '') { //此处为安卓下浏览器的一个坑，匹配正则有区别
            return null;
        } else {
            return decodeURIComponent(value);
        }
    },
    //替换链接上的参数值
    //url  替换链接
    //ref  替换的参数名
    //value 替换的值
    //replaceRouterParam  是否替换路由参数 false 默认替换非路由参数（非#后的参数）
    //  例 替换param1 http://xxx/a.html?param1=xxx&param2=xxx#/?param1=xxx  true替换 #后的param / false替换#前的参数
    changeURLPar: function(url, ref, value, replaceRouterParam) {
        var str = url;
        var routerAppend = '';
        var routerBefore = '';
        var searchBefore = '';
        var routerSplitIndex = str.indexOf('#');
        if (routerSplitIndex != -1) {
            routerAppend = url.substr(routerSplitIndex); //#后的数据，包括#
            routerBefore = url.substr(0, routerSplitIndex); //#前的数据，不包括#
            str = replaceRouterParam ? routerAppend : routerBefore; //替换路由后的参数，取routerAppend，否则取routerBefore
        } else { //原链接不带# 则按默认replaceRouterParam=false处理
            replaceRouterParam = false;
        }
        if (str.indexOf('?') != -1) { //参数串带?,则截取?后的数据
            searchBefore = str.substr(0, str.indexOf('?') + 1);
            str = str.substr(str.indexOf('?') + 1);
        } else { //不带?直接拼上
            var refv = str + "?" + ref + "=" + value;
            return replaceRouterParam ? (routerBefore + '#' + refv) : (refv + routerAppend);
        }
        var returnurl = "";
        var setparam = "";
        var arr;
        var modify = "0";

        if (str.indexOf('&') != -1) {
            //--start--新增--20181210  去除链接带的空值 例  a.html?x=1&y=2&z& ==> a.html?x=1&y=2
            arr = str.split('&');
            for (var j = 0; j < arr.length; j++) {
                var tp = arr[j];
                if (!tp || !tp.split('=')[1]) {
                    arr.splice(j, 1);
                    j = j - 1;
                }
            }
            str = arr.join('&');
            //--end
            arr = str.split('&');
            for (var i = 0; i < arr.length; i++) {
                var tmp = arr[i]; //保存临时值 key=value
                if (arr[i].split('=')[0] == ref) {
                    setparam = value;
                    modify = "1";
                } else {
                    setparam = tmp.replace(arr[i].split('=')[0] + '=', ''); //删除 “key=” ， 留下value字符串
                }
                returnurl = returnurl + arr[i].split('=')[0] + "=" + setparam + "&";
            }
            returnurl = returnurl.substr(0, returnurl.length - 1);
            if (modify == "0")
                if (returnurl == str)
                    returnurl = returnurl + "&" + ref + "=" + value;
        } else {
            if (str.indexOf('=') != -1) {
                var tmp = str;
                arr = str.split('=');
                if (arr[0] == ref) {
                    setparam = value;
                    modify = "1";
                } else {
                    setparam = tmp.replace(arr[0] + '=', '');
                }
                returnurl = arr[0] + "=" + setparam;
                if (modify == "0")
                    if (returnurl == str)
                        returnurl = returnurl + "&" + ref + "=" + value;
            } else
                returnurl = ref + "=" + value;
        }
        var result = replaceRouterParam ? (routerBefore + searchBefore + returnurl) : (searchBefore + returnurl + routerAppend);
        return result;
    },
    alert: function(tips, times, callback) {
        var optTimes = 2000;
        var localtion = 'bottom';
        if (times !== undefined) {
            optTimes = times;
        }

        if (!$("#util-pop-alert").length) {

            $("body").append('<div id="util-pop-alert" class="pop_alert"></div>');

            $("#util-pop-alert").css({
                position: 'fixed',
                left: '50%',
                bottom: '90px',
                background: 'rgba(89,89,89,.9)',
                color: '#fff',
                padding: '10px',
                opacity: '0',
                'text-align': 'center',
                '-webkit-transform': 'translate(-50%,0)',
                'transform': 'translate(-50%,0)',
                'z-index': '10009',
                'width': '68%',
                'border-radius': '7px',
                'line-height': '1.5',
                'word-break': 'break-all',
                'font-size': '16px',
                '-webkit-transition': 'all .3s ease-in'
            }).on('tap', function () {
                $("#util-pop-alert").css({opacity: '0'});
            });
        }

        setTimeout(function () {
            $("#util-pop-alert").html(tips).css({opacity: '1', 'pointer-events': 'all'});
        }, 0);

        setTimeout(function () {
            $("#util-pop-alert").css({opacity: '0', 'pointer-events': 'none'});
            if(callback) callback();
        }, optTimes);
    },
    //获取当前地理位置 依赖百度地图API
    getPositionCity: function (callBack) {
        var geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                var gc = new BMap.Geocoder();
                gc.getLocation(r.point, function(rs){
                    var addComp = rs.addressComponents;
                    var address =  addComp.province +  addComp.city + addComp.district + addComp.street + addComp.streetNumber;//获取地址
                    if(callBack) callBack(addComp.district);
                });
            }else {
                callBack('');
                $.alert('获取地理位置失败');
            }
        });
    },
    authIsLogin: function(noJump,redirect){
        var account = localStorage.getItem('myTel') || '';
        if(account) return true;
        if(!noJump){
            if(redirect) window.location.replace('./mobileLogin.html?redirect=1');
            else location.href = './mobileLogin.html';
        }
        return false
    },
    initSearchBar:function (search) {
        // 控制只加一个installBar
        var index = type || 0;
        if ($('#searchBar').length > 0) {
            return;
        }
        var searchHtml = '';
        $("body").append(installHtml);
        $("body").on("click", ".bottom_nav", function(e) {
            e.stopPropagation();
            e.preventDefault();

        });
    },
    addTiTleBar:function (title) {
        // 控制只加一个installBar
        if ($('#titleBar').length > 0) {
            return;
        }
        var installHtml = '<div id="titleBar" class="top_title_bar"><i class="btn_back" id="backBtn"></i>' +
            '<h3>'+title+'</h3>' +
            '</div>';
        $("body").prepend(installHtml);
        $("#backBtn").click(function () {
            history.go(-1);
        })
    },
    initNavBar:function (type) {
        // 控制只加一个installBar
        var index = type || 0;
        if ($('#bottomNavBar').length > 0) {
            return;
        }
        var installHtml = '<div id="bottomNavBar" class="bottom_nav_bar">' +
            '<div id="bottomHome" class="bottom_nav '+(index == 1?'active':'')+'" data-url="jobSearchList"><i class="home_logo"></i><p>主页</p></div>' +
            '<div id="bottomUser" class="bottom_nav '+(index == 2?'active':'')+'" data-url="userCenter"><i class="user_logo"></i><p>我的</p></div>' +
            '</div>';
        $("body").append(installHtml);
        $("body").css('padding-bottom','60px');
        $("body").on("click", ".bottom_nav", function(e) {
            e.stopPropagation();
            e.preventDefault();
            var url = $(this).attr('data-url');
            if(!$(this).hasClass('active')){
                window.location.replace('./'+url+'.html');
            }
        });
    }
});
(function() {
}());